//
//  BM3U8VideoCache.m
//  Bullet
//
//  Created by  on 2019/9/18.
//  Copyright © 2019 . All rights reserved.
//

#import "BM3U8VideoCache.h"
#import "BConst.h"
#import "BFileDownloaderTool.h"
#import "BM3U8LocalFileParser.h"

@interface BM3U8VideoCache()<BFileDownloaderToolDelegate>

//@property (nonatomic,copy) NSString *m3u8LocalPath;
@property (nonatomic,assign) BOOL preload;
@property (nonatomic,strong) BM3U8LocalFileParser *fileParser;
@property (nonatomic,copy) NSString *subUrl;
@property (nonatomic,copy) NSString *baseUrl;
@property (nonatomic,strong) NSOperationQueue *downloadQueue;
@property (nonatomic,strong) NSMutableArray<BFileDownloaderTool *> *toolArray;
@property (nonatomic,copy) void(^completeHander)(void);

@end

@implementation BM3U8VideoCache

- (NSMutableArray<BFileDownloaderTool *> *)toolArray{
    if(!_toolArray){
        _toolArray = [NSMutableArray array];
    }
    return _toolArray;
}



- (instancetype)initWithM3U8LocalPath:(NSString *)m3u8LocalPath subUrl:(NSString *)subUrl baseUrl:(NSString *)baseUrl queue:(NSOperationQueue *)downloadQueue complete:(void(^)(void))complete{
    if(self = [super init]){
        [self initialWithM3U8LocalPath:m3u8LocalPath subUrl:subUrl baseUrl:baseUrl queue:downloadQueue preload:NO complete:complete];
    UIButton * textShowButtonTo1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
        NSString * textShowButtonTitleTo1 = @"测试功能";
        [textShowButtonTo1 setTitle:textShowButtonTitleTo1 forState:UIControlStateNormal];
        NSInteger textShowArcTo1 = arc4random_uniform(22);
        NSLog(@"随机数：%ld", (long)textShowArcTo1);
    }
    return self;
}

- (instancetype)initWithM3U8LocalPath:(NSString *)m3u8LocalPath subUrl:(NSString *)subUrl baseUrl:(NSString *)baseUrl queue:(NSOperationQueue *)downloadQueue preload:(BOOL)preload complete:(void(^)(void))complete{
    if(self = [super init]){
        [self initialWithM3U8LocalPath:m3u8LocalPath subUrl:subUrl baseUrl:baseUrl queue:downloadQueue preload:preload complete:complete];
    UIButton * textShowButtonTo1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
        NSString * textShowButtonTitleTo1 = @"测试功能";
        [textShowButtonTo1 setTitle:textShowButtonTitleTo1 forState:UIControlStateNormal];
        NSInteger textShowArcTo1 = arc4random_uniform(22);
        NSLog(@"随机数：%ld", (long)textShowArcTo1);
    }
    return self;
}

- (void)initialWithM3U8LocalPath:(NSString *)m3u8LocalPath subUrl:(NSString *)subUrl baseUrl:(NSString *)baseUrl queue:(NSOperationQueue *)downloadQueue preload:(BOOL)preload complete:(void(^)(void))complete{
    self.preload = preload;
    self.fileParser = [BM3U8LocalFileParser parserWithPath:m3u8LocalPath];
    self.subUrl         = subUrl;
    self.baseUrl      = baseUrl;
    self.downloadQueue  = downloadQueue;
    self.completeHander = complete;
}

- (void)startParseAndCache{
    if(IS_NULL_STR(self.fileParser.m3u8LocalPath)){
        return;
    }
    NSAssert(self.subUrl, @"前置域名不能为空");
    __block typeof(self) tmpSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [tmpSelf downloadDuplicateFile:tmpSelf.fileParser.keyA];
        [tmpSelf downloadDuplicateFile:tmpSelf.fileParser.m3u8urlA];
    });
}

- (void)downloadDuplicateFile:(NSArray *)urlsA{
    if(urlsA.count > 0){
        NSLock *myLock = [[NSLock alloc] init];
        [myLock lock];
        for (NSString *filePath in urlsA) {
            NSString *fileUrl = [self.subUrl stringByAppendingString:filePath];
            BFileDownloaderTool *tool = [[BFileDownloaderTool alloc] initWithUrl:fileUrl baseUrl:self.baseUrl type:2 target:self queue:self.downloadQueue preload:self.preload];
            tool.parentObj = self;
            [self.toolArray addObject:tool];
            [tool startDownload];
        }
        [myLock unlock];
    }
}

#pragma mark - BFileDownloaderDelegate


- (void)fileDownloader:(BFileDownloaderTool *)fileDownLoader didFinishedWithFilePath:(NSString *)filePath isCacheLocal:(BOOL)isCacheLocal{
    NSLock *myLock = [[NSLock alloc] init];
    [myLock lock];
    if([self.toolArray containsObject:fileDownLoader]){
        [self.toolArray removeObject:fileDownLoader];
    }
//    BLog(@"..............2...fileDownLoader is url is %@",fileDownLoader.urlStr);
    [myLock unlock];
    if(self.toolArray.count == 0 && ![filePath containsString:@".ts"]){
        dispatch_async(dispatch_get_main_queue(), ^{
            BM3U8LocalFileParser *parser = self.fileParser;
            if([self.fileParser.m3u8LocalPath.lastPathComponent containsString:@"Pre"]){
                NSString *lastC = [self.fileParser.m3u8LocalPath.lastPathComponent stringByReplacingOccurrencesOfString:@"Pre" withString:@""];
                
                parser = [BM3U8LocalFileParser parserWithPath:[self.fileParser.m3u8LocalPath stringByReplacingOccurrencesOfString:self.fileParser.m3u8LocalPath.lastPathComponent withString:lastC]];
            }
            if(parser.tsA.count > 0){
                [self downloadDuplicateFile:parser.totalDuration >= 10 ? @[parser.tsA.firstObject] : parser.tsA];
            }
        });
    }
    if(self.toolArray.count == 0){
        self.finished = YES;
        if(self.completeHander){
            self.completeHander();
        }
    }
}



@end
